"""
selenium 获取cookie
浏览器对象.get_cookies()


"""
import json
import time

from selenium import webdriver
from selenium.webdriver.common.by import By

options=webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches',['enable-automation'])
options.add_argument('--incognito')
from selenium import webdriver
def crawl_cookie():
    driver=webdriver.Chrome(executable_path=r"D:\六星教育\2203期\2022_3_python\13.selenium使用2\代码\chromedriver.exe",options=options)
        # 打开笔趣阁
    driver.get("https://www.qbiqu.com/")
    # 睡眠3秒
    time.sleep(3)
    username=driver.find_element(By.XPATH,'//*[@id="username"]')
    username.send_keys("jiuhaoyyds")
    password=driver.find_element(By.XPATH,'//*[@id="password"]')
    password.send_keys("qwe123")
    click_=driver.find_element(By.CLASS_NAME,'int')
    click_.click()
    print(username)
    time.sleep(5)
    # 获取登陆后有用户身份的cookie 返回的时字典类型数据 要进行dumps方法
    # 就直接用 get_cookies()
    cookie=driver.get_cookies()
    datass=json.dumps(cookie)
    # 需对cookie进行写入
    with open("cookie_w2.cookie","w",encoding="utf-8") as f:
        f.write(datass)

    data=driver.page_source
    driver.close()
    # 关闭浏览器
    driver.quit()

# 通过添加cookie访问网页
def set_cookie():
    driver = webdriver.Chrome(executable_path=r"D:\六星教育\2203期\2022_3_python\13.selenium使用2\代码\chromedriver.exe",options=options)
    with open("cookie_w2.cookie","r",encoding="utf-8") as f:
        cookiessss=json.loads(f.read())
    # 打开笔趣阁
    driver.get("https://www.qbiqu.com/")
#     将cookie进行循环写入
    for cookie in cookiessss:
        # 需要更改 domain参数
        cookie_dict = {
            'domain': '.qbiqu.com',
            'name': cookie.get('name'),
            'value': cookie.get('value'),
            "expires": '',
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False}
        driver.add_cookie(cookie_dict)
#     刷新
    driver.refresh()
    time.sleep(3)
    driver.close()
    driver.quit()

if __name__ == '__main__':
    # crawl_cookie()
    set_cookie()




